package com.itheima.case2.web;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.lang.reflect.Method;

// BaseServlet就是一个工具类而已, 无需配置路径
//@WebServlet("/BaseServlet")
public class BaseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置请求和响应编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        //1.获取方法名
        String url = request.getRequestURI();
        int lastIndex = url.lastIndexOf('/');
        String method = url.substring(lastIndex + 1, url.length());

        try {
            //a. 找到方法所在的类
            Class<?> clazz = this.getClass();
            // b. 找到方法名为method值,参数为HttpServletRequest和HttpServletResponse
            Method m = clazz.getDeclaredMethod(method, HttpServletRequest.class, HttpServletResponse.class);
            //c. 调用m方法
            m.setAccessible(true);
            //等价于 this.m(request,response)
            m.invoke(this,request,response);
        }  catch (Exception e) {
            e.printStackTrace();
        }
    }
}
